#include "cursor.h"

namespace SEL
{

Cursor::Cursor (Surface *surface, int hot_x, int hot_y)
    : m_surface (surface), m_hot_x (hot_x), m_hot_y (hot_y)
{
	if (m_surface)
		m_surface->ref ();
}

Cursor::~Cursor ()
{
	releaseSurface ();
}

void
Cursor::setSurface (Surface *surface)
{
	releaseSurface ();
	m_surface = surface;
	if (m_surface)
		m_surface->ref ();
}

void
Cursor::releaseSurface ()
{
	if (m_surface)
		m_surface->unref ();
	m_surface = NULL;
}

void
Cursor::setHotX (int hot_x)
{
	m_hot_x = hot_x;
}

ResourceCursor::ResourceCursor (const std::string &name,
			        const std::string &location,
			        const ResourceProperties &properties)
	: ResourceSurface (name, location, properties)
{
	m_cursor = NULL;
	m_type = "cursor";
}

ResourceCursor::~ResourceCursor ()
{
	if (loaded ())
		free ();
}

void
ResourceCursor::load (RWops & ops)
{
	if (loaded ())
		free ();
	
	ResourceSurface::load (ops);
	
	int hot_x = 0;
	if (m_properties.exists ("hot_x"))
		hot_x = m_properties.get ("hot_x").asInteger ();
		
	int hot_y = 0;
	if (m_properties.exists ("hot_y"))
		hot_y = m_properties.get ("hot_y").asInteger ();
		
	m_cursor = new Cursor (m_surface, hot_x, hot_y);
	
	ResourceSurface::free ();
}

void
ResourceCursor::free ()
{
	if (m_cursor)
		m_cursor->unref ();
	m_cursor = NULL;
}

Cursor * 
getCursor (Resource *res)
{
	if (!res || res->type () != "cursor")
		throw (Error ("Invalid resource type!\n"));
	return (Cursor*) res->data ();
}

}; // namespace SEL
